package com.douwong.student.popuwindow;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.bumptech.glide.Glide;
import com.douwong.student.R;
import com.douwong.student.activity.ImageActivity;
import com.douwong.student.model.ResTestProblemsInfo;
import com.douwong.student.utils.ImagFilterUtil;
import com.douwong.student.utils.UIUtils;
import com.douwong.student.view.FlowLayout;
import com.douwong.student.view.MTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 课堂练习popuWindow
 */

public class ShowSubjectDetailPopuWindow extends PopupWindow {
    private static final String TAG = ShowSubjectDetailPopuWindow.class.getSimpleName();
    private final ResTestProblemsInfo.TopicItemBean topicItemBean;
    private ListView mListView;
    private View view;
    private View mHeadView;
    private MTextView mTitle;
    private FlowLayout mImageRoot;
    private Context mContext;

    private int mCurrentPositon;
    private int mTitlePosition;

    public ShowSubjectDetailPopuWindow(Context context, ResTestProblemsInfo.TopicItemBean topicItemBean) {
        mContext = context;
        this.topicItemBean=topicItemBean;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.show_new_subject_activity, null);
        mHeadView = inflater.inflate(R.layout.head_show_subject_popuwindow, null);

        initView();
        setValue();
        this.setContentView(view);
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0xffffff);
        this.setBackgroundDrawable(dw);
    }

    private void initView() {
        mTitle = (MTextView) mHeadView.findViewById(R.id.text_new_showsubject_popuwindow_title);
        mImageRoot = (FlowLayout) mHeadView.findViewById(R.id.ll_new_showsubject_popuwindow_imagroot);
        mListView = (ListView) view.findViewById(R.id.listview_newshow_subject_popu);
    }
    private void setValue() {
        //listveiw添加点击事件
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //
                dismiss();
            }
        });

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        //判断数据类型

        ImagFilterUtil.filterMTImage(mTitle, "("+topicItemBean.getTopicType().getTypeName()+")"+topicItemBean.getBody());
        final ArrayList<String> listUrl = (ArrayList<String>) ImagFilterUtil.filterUrl(topicItemBean.getBody());//获取图片路径
        if (listUrl.size() > 0) {
            ImageView imageview;
            for (int i = 0; i < listUrl.size(); i++) {
                mTitlePosition = i;

                Log.i(TAG, listUrl.get(i));
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UIUtils.dip2px(150), UIUtils.dip2px(150));

                params.leftMargin = 20;
                imageview = new ImageView(mContext);
                mImageRoot.addView(imageview, params);
              //  ImageLoader.getInstance().displayImage(listUrl.get(i), imageview, DisplayImageOptionsUtil.getDefaultOption());

                Glide.with(mContext).load(listUrl.get(i)).placeholder(R.mipmap.answerdefault).into(imageview);
                imageview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                      //  openLargePhoto(mContext,listUrl.get(mTitlePosition));
                        Intent intent=new Intent();
                        intent.setClass(mContext, ImageActivity.class);
                        intent.putStringArrayListExtra("imgs", listUrl);
                        intent.putExtra("position",mTitlePosition);
                        mContext.startActivity(intent);
                    }
                });
            }
        }

        //listview显示
        mListView.addHeaderView(mHeadView);
        setListViewHeightBasedOnChildren(mListView);
        mListView.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {

                if (topicItemBean.getTopicType().getItemType()==3) {
                    return 0;
                }if (topicItemBean.getTopicType().getItemType()==15){
                    return 0;
                }

                if (topicItemBean.getOptions().size() > 0) {
                    return topicItemBean.getOptions().size();
                }
                return 0;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder = null;
                if (convertView == null) {
                    holder = new ViewHolder();
                    convertView = View.inflate(mContext, R.layout.head_show_subject_popuwindow, null);
                    holder.textViewTiele = (MTextView) convertView.findViewById(R.id.text_new_showsubject_popuwindow_title);
                    holder.mLinearLayoutRoot = (FlowLayout) convertView.findViewById(R.id.ll_new_showsubject_popuwindow_imagroot);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                holder.textViewTiele.setTextColor(Color.parseColor("#333333"));

                holder.mLinearLayoutRoot.removeAllViews();
                String title = topicItemBean.getOptions().get(position).getKey() + "." + topicItemBean.getOptions().get(position).getValue();
                ImagFilterUtil.filterMTImage(holder.textViewTiele, title);
                final ArrayList<String> list = (ArrayList<String>) ImagFilterUtil.filterUrl(topicItemBean.getOptions().get(position).getValue());
                Log.i(TAG, "截取的图片数量：" + list.size());
                if (list.size() > 0) {
                    ImageView itemImage = null;
                    for (int i = 0; i < list.size(); i++) {
                        //	Log.i(TAG,listUrl.get(i));
                        mCurrentPositon = i;
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UIUtils.dip2px(150), UIUtils.dip2px(150));
                        params.leftMargin = 20;
                        itemImage = new ImageView(mContext);
                        holder.mLinearLayoutRoot.addView(itemImage, params);
                     //   ImageLoader.getInstance().displayImage(list.get(i), itemImage, DisplayImageOptionsUtil.getDefaultOption());
                        Glide.with(mContext).load(list.get(i)).placeholder(R.mipmap.answerdefault).into(itemImage);
                        itemImage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                               // Toast.makeText(mContext, "进入大图", Toast.LENGTH_SHORT).show();
                              //  openLargePhoto(mContext, list.get(mCurrentPositon));
                                Intent intent=new Intent();
                                intent.setClass(mContext, ImageActivity.class);
                                intent.putStringArrayListExtra("imgs", list);
                                intent.putExtra("position",mCurrentPositon);
                                mContext.startActivity(intent);
                            }
                        });
                    }
                }

                return convertView;
            }
        });
    }

    //此方法在setAdapter之前调用
    private void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
    /**
     * 进入大图浏览
     *
     * @param context
     * @param urls 选中的图片的url
     */
    private void openLargePhoto(Context context, String urls) {
        String itemBody = topicItemBean.getBody();//题目

        List<String> mTitlData = ImagFilterUtil.filterUrl(itemBody);
            for (int i = 0; i < topicItemBean.getOptions().size(); i++) {
                String answerValue =  topicItemBean.getOptions().get(i).getValue();
                List<String> list = ImagFilterUtil.filterUrl(answerValue);
                if (list.size()>0){
                    for (String url : list) {
                        mTitlData.add(url);
                        Log.i(TAG,"新的"+url);

                    }
                }
        }
        int positon=mTitlData.indexOf(urls);
      //  String serialize = JsonUtils.toJson(mTitlData);
     //   GroupTalkLargePhotoActivity.openGroupTalkPhotoActivity(context,serialize,positon);

    }

    private class ViewHolder {
        MTextView textViewTiele;
        FlowLayout mLinearLayoutRoot;
    }
}
